﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using 新门禁.Model;
using GuardMonitor.Utils;
using 新门禁.Utils;

namespace 新门禁
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public static BaseInfo baseInfo;
        public static GlobalVariablesModel globalVariables = null;
        private static object _lock = new object();

        public static HttpServer httpServer = null;
        public static log4net.ILog operationLog = log4net.LogManager.GetLogger("OperationLog");
        public static log4net.ILog errorLog = log4net.LogManager.GetLogger("ErrorLog");


        public static BaseInfo GetBaseInfo()
        {
            if (baseInfo == null)
            {
                lock (_lock)
                {
                    if (baseInfo == null)
                    {
                        baseInfo = new BaseInfo();
                        baseInfo.gateCode = ConfigurationManager.AppSettings["GateCode"];
                        baseInfo.HttpServerIp = ConfigurationManager.AppSettings["HttpServerIp"];
                        baseInfo.HttpServerPort = ConfigurationManager.AppSettings["HttpServerPort"];
                        baseInfo.AuthHttpServerPort = ConfigurationManager.AppSettings["AuthHttpServerPort"];

                        baseInfo.IO_Com_PortName = ConfigurationManager.AppSettings["IO_Com_PortName"];
                        baseInfo.IO_In_Open_Port = ConfigurationManager.AppSettings["IO_In_Open_Port"];
                        baseInfo.IO_In_Close_Port = ConfigurationManager.AppSettings["IO_In_Close_Port"];
                        baseInfo.IO_Out_Open_Port = ConfigurationManager.AppSettings["IO_Out_Open_Port"];
                        baseInfo.IO_Out_Close_Port = ConfigurationManager.AppSettings["IO_Out_Close_Port"];
                        baseInfo.DIDO_IP = ConfigurationManager.AppSettings["DIDO_IP"];

                        baseInfo.Camera_In_VideoUrl = ConfigurationManager.AppSettings["Camera_In_VideoUrl"];
                        baseInfo.Camera_Out_VideoUrl = ConfigurationManager.AppSettings["Camera_Out_VideoUrl"];

                        baseInfo.LocalHttpServerPort = int.Parse(ConfigurationManager.AppSettings["LocalHttpServerPort"]);

                        baseInfo.RefreshSeconds = int.Parse(ConfigurationManager.AppSettings["RefreshSeconds"]);
                        baseInfo.BoudRate = ConfigurationManager.AppSettings["boudRate"];
                        baseInfo.ButtonLimit = ConfigurationManager.AppSettings["ButtonLimit"];
                        baseInfo.SamplingIp = ConfigurationManager.AppSettings["SamplingIp"];
                        baseInfo.IdReadCardTime = ConfigurationManager.AppSettings["IdReadCardTime"];

                    }
                }
            }
            return baseInfo;
        }

        public static GlobalVariablesModel GetGlobalVariablesModel()
        {
            if (globalVariables == null)
            {
                lock (_lock)
                {
                    if (globalVariables == null)
                    {
                        globalVariables = new GlobalVariablesModel();
                    }
                }
            }
            return globalVariables;
        }

        public static HttpServer GetHttpServer()
        {
            if (httpServer == null)
            {
                lock (_lock)
                {
                    if (httpServer == null)
                    {
                        int port = GetBaseInfo().LocalHttpServerPort;
                        httpServer = new HttpServer(port);
                    }
                }
            }

            return httpServer;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            
            base.OnStartup(e);
            
            int port = GetBaseInfo().LocalHttpServerPort;
            HttpServer server = GetHttpServer();
            if (!server.IsListening())
            {
                server.Run();
            }
            //LogHelper.InitLog4Net();
            RegisterEvents();
        }
        private void RegisterEvents()
        {
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            //UI线程未捕获异常处理事件（UI主线程）
            DispatcherUnhandledException += App_DispatcherUnhandledException;

            //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }

        //Task线程内未捕获异常处理事件
        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            try
            {
                if (e.Exception is Exception exception)
                {
                    HandleException(exception);
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                e.SetObserved();
            }
        }

        //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                if (e.ExceptionObject is Exception exception)
                {
                    HandleException(exception);
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        //UI线程未捕获异常处理事件（UI主线程）
        private static void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                HandleException(e.Exception);
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                e.Handled = true;
            }
        }

        //日志记录
        private static void HandleException(Exception ex)
        {
            //记录日志
            LogHelper.WriteInfoLog(ex.Message);
            Current.Shutdown();
        }

        //private void RegisterEvents()
        //{
        //    //Task线程内未捕获异常处理事件
        //    TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

        //    //UI线程未捕获异常处理事件（UI主线程）
        //    this.DispatcherUnhandledException += App_DispatcherUnhandledException;

        //    //非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
        //    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        //}

        //private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        //{
        //    try
        //    {
        //        var exception = e.Exception as Exception;
        //        if (exception != null)
        //        {
        //            HandleException(exception);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        HandleException(ex);
        //    }
        //    finally
        //    {
        //        e.SetObserved();
        //    }
        //}

        ////非UI线程未捕获异常处理事件(例如自己创建的一个子线程)      
        //private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        //{
        //    try
        //    {
        //        var exception = e.ExceptionObject as Exception;
        //        if (exception != null)
        //        {
        //            HandleException(exception);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        HandleException(ex);
        //    }
        //    finally
        //    {
        //        //ignore
        //    }
        //}

        ////UI线程未捕获异常处理事件（UI主线程）
        //private static void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        //{
        //    try
        //    {
        //        HandleException(e.Exception);
        //    }
        //    catch (Exception ex)
        //    {
        //        HandleException(ex);
        //    }
        //    finally
        //    {
        //        //处理完后，我们需要将Handler=true表示已此异常已处理过
        //        e.Handled = true;
        //    }
        //}
        //private static void HandleException(Exception e)
        //{
        //    MessageBox.Show("程序异常：" + e.Source + "@@" + Environment.NewLine + e.StackTrace + "##" + Environment.NewLine + e.Message);
        //    //记录日志
        //    // Utils.LogWrite(e);

        //}

    }
}
